package vn.com.mybudget.base;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;

public class XMLView extends ViewBase {
	private JAXBContext jaxbContext;
	private Marshaller jaxbMarshaller;
	public XMLView(Object model) {
		super(model);
	}
	
	@Override
	public void Process(HttpServletRequest currentRequest,
			HttpServletResponse currentResponse) {
		try {
	    	if (jaxbContext== null){
	    		jaxbContext = JAXBContext.newInstance(this.Model.getClass());	
	    	}
	    	if (jaxbMarshaller == null){
	    		jaxbMarshaller = (Marshaller) jaxbContext.createMarshaller();
	    		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	    	}
	    	
	    	//Set response type as xml
	    	currentResponse.setContentType("text/xml;charset=UTF-8");
	    	//Write object as xml
	    	jaxbMarshaller.marshal(this.Model,currentResponse.getWriter());
	    	
			} catch (PropertyException e) {
				try {
					currentResponse.getWriter().print("XMLView.Process Exception: "+e.getMessage());
					e.printStackTrace(currentResponse.getWriter());
				} catch (IOException e1) {
				}
			}
			catch (JAXBException e) {
				try {
					currentResponse.getWriter().print("XMLView.Process Exception: "+e.getMessage());
					e.printStackTrace(currentResponse.getWriter());
				} catch (IOException e1) {
				}
			} catch (IOException e) {
				try {
					currentResponse.getWriter().print("XMLView.Process Exception: "+e.getMessage());
					e.printStackTrace(currentResponse.getWriter());
				} catch (IOException e1) {
				}
			}
	}
}
